import React from 'react';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';

interface Props {
  content: string;
}

// 初始化Markdown解析器
const md = new MarkdownIt({
  html: false,
  xhtmlOut: false,
  breaks: false,
  langPrefix: 'language-',
  linkify: true,
});

const renderLaguage = ['javascript', 'python', 'java', 'go', 'css'];

// 代码高亮
function codeHighLight(md: MarkdownIt) {
  md.renderer.rules.fence = (tokens: any[], idx: number) => {
    const token = tokens[idx];
    const lang = token.info.trim().toLowerCase();
    const code = token.content;
    if (!renderLaguage.includes(lang)) {
      return `<pre class="hljs"><code class="language-${lang}">${code}</code></pre>\n`;
    }
    const highlightedCode = hljs.highlight(code, { language: lang }).value;
    return `<pre class="hljs"><code class="language-${lang}">${highlightedCode}</code></pre>\n`;
  };
}

// 使用组件
md.use(codeHighLight);

const MarkdownRenderer: React.FC<Props> = ({ content }) => {
  const htmlContent = md.render(content);

  return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
};
export default MarkdownRenderer;
